#!/usr/bin/env bash
set -e

for version in "$RBENV_ROOT"/versions/*; do
  shopt -s nullglob
  gemsets=("$version"/gemsets/* "$version"/gemsets/.project-gemsets/*)
  shopt -u nullglob

  if [ -n "$gemsets" ]; then
    echo ${version##*/}:
    project_gemset="^$version/gemsets/.project-gemsets/"
    for gemset in "${gemsets[@]}"; do
      if [[ $gemset =~ $project_gemset ]]; then
        location=${gemset##*/}
        if [[ -e $gemset ]]; then
          echo "  ${location//__//}"
        else
          rm "$gemset"
        fi
      else
        echo "  ${gemset##*/}"
      fi
    done
  fi
done
